package com.enation.app.javashop.core.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.system.model.dos.LogisticsCompanyDO;
import com.enation.app.javashop.core.trade.cart.model.dos.OrderPermission;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.model.vo.DeliveryVO;
import com.enation.app.javashop.core.trade.order.service.OrderOperateManager;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zhou
 * @Date: 2020/12/1
 * @Description:
 */
@Slf4j
public class ShipOrderDataListener extends AnalysisEventListener<ShipOrderImport> {

    private OrderOperateManager orderOperateManager;

    private DaoSupport daoSupport;

    private List<ShipOrderImport> importList = new ArrayList<>();
    public static List<ShipOrderImport> errorList = new ArrayList<>();

    public ShipOrderDataListener(OrderOperateManager orderOperateManager, DaoSupport daoSupport) {
        this.orderOperateManager = orderOperateManager;
        this.daoSupport = daoSupport;
    }

    @Override
    public void invoke(ShipOrderImport shipOrderImport, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(shipOrderImport));
        importList.add(shipOrderImport);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        if (CollectionUtils.isEmpty(importList)) {
            // throw new ServiceException("601", "批量导入发货文件为空");
            return;
        }

        // 1、查询所有的订单信息
        List<String> orderSnList = importList.stream().filter(shipOrderImport -> !StringUtil.isEmpty(shipOrderImport.getOrderSn()))
                .map(ShipOrderImport::getOrderSn).collect(Collectors.toList());
        String orderSnString = StringUtil.arrayToString(orderSnList.toArray(), ",");
        String orderSql = "select * from es_order where order_status = '" + OrderStatusEnum.PAID_OFF + "' and sn in (" + orderSnString + ")";
        List<OrderDO> orderDOList = this.daoSupport.queryForList(orderSql, OrderDO.class);

        if (CollectionUtils.isEmpty(orderDOList)) {
            // throw new ServiceException("602", "当前订单状态不能发货");
            return;
        }

        //如果订单不为空，转为map key为订单编号，value为快递类型
        Map<String, String> shippingTypeMap = orderDOList.stream().collect(Collectors.toMap(OrderDO::getSn, OrderDO::getShippingType));

        // 2、获取所有的快递公司
        String logiSql = "select * from es_logistics_company";
        List<LogisticsCompanyDO> logiList = this.daoSupport.queryForList(logiSql, LogisticsCompanyDO.class);
        if (CollectionUtils.isEmpty(logiList)) {
            // throw new ServiceException("603", "系统没有配置快递公司，请联系管理员");
            return;
        }

        // 3、转为map,key为快递公司名
        Map<String, Integer> logiMap = logiList.stream().collect(Collectors.toMap(LogisticsCompanyDO::getName, LogisticsCompanyDO::getId, (oldValue, newValue) -> newValue));

        //4、循环调用发货的方法
        for (ShipOrderImport shipOrderImport : importList) {
            //4.1、检测shipOrderImport对象中是否有值
            if (this.check(shipOrderImport)) {
                // 4.2封装信息
                DeliveryVO deliveryVO = new DeliveryVO();
                deliveryVO.setOrderSn(shipOrderImport.getOrderSn());
                deliveryVO.setOperator("平台管理员批量发货");

                //4.3、获取订单配送类型，赋不同的值
                String shipType = shippingTypeMap.get(shipOrderImport.getOrderSn());
                deliveryVO.setShipType(shipType);
                if (shipType.equals(ShipTypeEnum.SELF.name())) {
                    deliveryVO.setLogiId(0);
                    deliveryVO.setLogiName("自提配送");
                    deliveryVO.setDeliveryNo("00000");
                } else {
                    //4.4、获取快递公司的ID，如果为空则说明数据有问题，把对象放进错误的列表
                    Integer logiId = logiMap.get(shipOrderImport.getLogiName());
                    if (logiId == null) {
                        errorList.add(shipOrderImport);
                        continue;
                    }

                    deliveryVO.setLogiId(logiId);
                    deliveryVO.setLogiName(shipOrderImport.getLogiName());
                    deliveryVO.setDeliveryNo(shipOrderImport.getShipNo());
                }

                // 5、调用发货方法
                orderOperateManager.ship(deliveryVO, OrderPermission.admin);
            } else {
                errorList.add(shipOrderImport);
                continue;
            }
        }

    }

    private boolean check(ShipOrderImport shipOrderImport) {
        if (StringUtil.isEmpty(shipOrderImport.getLogiName())) {
            return false;
        }
        if (StringUtil.isEmpty(shipOrderImport.getOrderSn())) {
            return false;
        }
        if (StringUtil.isEmpty(shipOrderImport.getShipNo())) {
            return false;
        }
        return true;
    }
}
